import 'dart:io';

import 'package:flutter/material.dart';

import 'package:get/get.dart';
import 'package:photo_view/photo_view.dart';
import 'package:photo_view/photo_view_gallery.dart';

import '../../../widgets/image/kq_image.dart';
import '../../../widgets/imageBox/kq_image_box.dart';
import '../../../widgets/titleBar/kq_title_bar.dart';
import 'controller.dart';

/// 图片预览界面
class ImgPreviewPage extends StatelessWidget {
  const ImgPreviewPage({super.key});

  _buildProvider(ImageUrl imageUrl) {
    switch (imageUrl.imageType) {
      case ImageType.file:
        return FileImage(File(imageUrl.url));
      case ImageType.http:
        return NetworkImage(imageUrl.url);
      case ImageType.assets:
        return AssetImage(imageUrl.url);
    }
  }

  @override
  Widget build(BuildContext context) {
    final controller = Get.put(ImgPreviewController());
    final state = Get.find<ImgPreviewController>().state;

    var pageIndex = state.position;

    var pageController = PageController(initialPage: state.position);

    return GetBuilder(
      init: controller,
      builder: (controller) => Scaffold(
        backgroundColor: Colors.black,
        appBar: KqHeadBar(
          showBack: true,
          bgColor: Colors.black,
          back: () {
            Get.back();
          },
          headTitle: '${pageIndex + 1}/${state.imageUrls.length}',
        ),
        body: PhotoViewGallery.builder(
          scrollPhysics: const BouncingScrollPhysics(),
          builder: (BuildContext context, int index) {
            var imageUrl = state.imageUrls[index];
            return PhotoViewGalleryPageOptions(
              imageProvider: _buildProvider(imageUrl),
              initialScale: PhotoViewComputedScale.contained * 1.0,
              heroAttributes: PhotoViewHeroAttributes(tag: imageUrl.url),
            );
          },
          pageController: pageController,
          itemCount: state.imageUrls.length,
          onPageChanged: (index) {
            pageIndex = index;
            controller.update();
          },
          loadingBuilder: (context, event) => Center(
            child: SizedBox(
              width: 20,
              height: 20,
              child: CircularProgressIndicator(
                value: event == null
                    ? 0
                    : event.cumulativeBytesLoaded / event.expectedTotalBytes!,
              ),
            ),
          ),
        ),
      ),
    );
  }
}
